package org.ix.shiro.shiro;

import org.ix.common.models.ResponseError;
import org.ix.common.utils.JsonUtils;
import org.ix.common.utils.RequestUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class IxAuthenticatingFilter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token
        String token = RequestUtils.getToken((HttpServletRequest) request);
        return new IxAuthenticationToken(token);
    }

    /**
     * 是否允许访问
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());
    }

    /**
     * 是否拒绝访问
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return executeLogin(request, response);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        try {
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            setResponse((HttpServletRequest) request, (HttpServletResponse) response, throwable.getMessage());
        } catch (IOException ignored) {
        }

        return false;
    }

    private static void setResponse(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String message) throws IOException {
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
        httpResponse.setHeader("Content-type", "application/json");
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        ResponseError responseError = new ResponseError();
        responseError.setMessage(message);
        httpResponse.getWriter().print(JsonUtils.toJsonString(responseError));
    }
}
